package com.chuanjiabao.wisdom.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.InheritCallBackBean;
import com.chuanjiabao.wisdom.bean.UpdateFileTeam;
import com.chuanjiabao.wisdom.databinding.FragmentThirdBinding;
import com.chuanjiabao.wisdom.greendao.gen.UpdateFileTeamDao;
import com.chuanjiabao.wisdom.ui.activity.FeedbackActivity;
import com.chuanjiabao.wisdom.ui.activity.InputClockPwdActivity;
import com.chuanjiabao.wisdom.ui.activity.SuccessorActivity;
import com.chuanjiabao.wisdom.ui.activity.SuccessorSelectActivity;
import com.chuanjiabao.wisdom.ui.activity.UpdateFileActivity;
import com.chuanjiabao.wisdom.ui.activity.UserActivity;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.chuanjiabao.wisdom.bean.Constants.REQEEST_CDOE_GPS;
import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE;

public class ThirdFragment extends BaseLazyFragment {

    private FragmentThirdBinding binding;
    private List<UpdateFileTeam> list = new ArrayList<>();
    private boolean isGet = false;

    private UpdateFileTeamDao teamDao =
            FApplication.getInstance()
                    .getDaoSession()
                    .getUpdateFileTeamDao();

    @Override
    public int setLayoutId() {
        return R.layout.fragment_third;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(
                LayoutInflater.from(getActivity()),
                R.layout.fragment_third,
                container,
                false
        );
        binding.setFragment(this);
        return binding.getRoot();
    }

    @Override
    protected void onVisible() {
        isGet = false;
    }

    @Override
    protected void lazyLoad() {
        //获取存储量
        getStorage();

        isGet = true;
        //开启子线程获取图片数量
        Runnable runnable = () -> {
            while (isGet) {
                list = teamDao.loadAll();
                if (list.size() != 0) {
                    Message msg = Message.obtain();
                    msg.what = REQUEST_CODE;
                    msg.obj = list.size() + " " + list.get(0).getFileName() + " " + list.get(0).getFileType();
                    handler.sendMessage(msg);
                } else {
                    handler.sendEmptyMessageDelayed(REQEEST_CDOE_GPS, 500);
                }

                SystemClock.sleep(2000);
            }
        };

        BHThreadPool.getInstance().executeTask(runnable);

        binding.llModuleClock.setOnClickListener(this);
        binding.llModuleReasionInfo.setOnClickListener(this);
        binding.llModuleSuccessor.setOnClickListener(this);
        binding.llModuleNoUpdate.setOnClickListener(this);
        binding.llModuleUpdate.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
        binding.llModueFeed.setOnClickListener(this);
        binding.llModuleUpdate.setVisibility(View.GONE);
    }

    @Override
    public void onResume() {
        super.onResume();
        GlideUtil.setCircleMethod(getContext(), SpResourceUtil.getHead(), binding.ivModuleHead);
        binding.tvModuleTrueName.setText(SpResourceUtil.getTrueName());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivModuleHead:
            case R.id.llModuleReasionInfo:
                startActivity(new Intent(getActivity(), UserActivity.class));
                break;
            case R.id.llModuleNoUpdate:
            case R.id.llModuleUpdate:
                startActivity(new Intent(getActivity(), UpdateFileActivity.class));
                break;
            case R.id.llModuleSuccessor:
                getInherit();
                break;
            case R.id.llModuleClock:
                startActivity(new Intent(getActivity(), InputClockPwdActivity.class));
                break;
            case R.id.llModueFeed:
                startActivity(new Intent(getActivity(), FeedbackActivity.class));
                break;
        }
    }

    private void getStorage() {
        HTTPAPI.getInstance().setStorage(new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    try {
                        JSONObject json = new JSONObject(s);
                        if (json.has("data")) {
                            JSONObject obj = json.getJSONObject("data");
                            if (obj.has("used") && obj.has("total")) {
                                String used = obj.optString("used");
                                String total = obj.optString("total");
                                if (TextUtils.isEmpty(used)) used = "0";
                                if (TextUtils.isEmpty(total)) total = "0";
                                long usedLong = Long.parseLong(used);
                                long totalLong = Long.parseLong(total);
                                int pressent = (int) (usedLong * 1.0 / totalLong * 100);
                                binding.tvModuleUsed.setText(
                                        new BigDecimal(usedLong * 1.0 / 1024)
                                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue() + "G");
                                binding.tvModuleTotal.setText(
                                        new BigDecimal(totalLong * 1.0 / 1024)
                                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue() + "G");
                                binding.pBModule.setProgress(pressent);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void getInherit() {
        showProgressDialog("");
        HTTPAPI.getInstance().getInherit(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                cancelProgressDialog();
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(getActivity(), s);
                } else {
                    InheritCallBackBean bean = GsonUtil.GsonToBean(s, InheritCallBackBean.class);
                    if (bean != null && bean.getData() != null) {
                        InheritCallBackBean.DataBean data = bean.getData();
                        switch (data.getInherit()) {
                            case 1:
                                Intent intent1 = new Intent(getActivity(), SuccessorActivity.class);
                                intent1.putExtra("data", data);
                                startActivity(intent1);
                                break;
                            case 2:
                            case 3:
                                Intent intent2 = new Intent(getActivity(), SuccessorSelectActivity.class);
                                intent2.putExtra("data", data);
                                startActivity(intent2);
                                break;
                            case 4:
                                ToastUtil.showToast("您还没有创建家，无法操作！");
                                break;
                        }
                    }
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_CODE:
                    String result = (String) msg.obj;
                    String[] res = result.split(" ");
                    binding.llModuleNoUpdate.setVisibility(View.GONE);
                    binding.llModuleUpdate.setVisibility(View.VISIBLE);
                    binding.tvModuleFileUpdate.setText(res[0] + "项文件");

                    String oldUrl = (String) binding.ivModuleUpdate.getTag(R.id.image_tag);
                    if (!TextUtils.equals(oldUrl, res[1])) {
                        if (getActivity() != null) {
                            GlideUtil.setRoundUriMethod(
                                    getActivity(),
                                    res[1],
                                    binding.ivModuleUpdate,
                                    5
                            );
                        }
                        binding.ivModuleUpdate.setTag(R.id.image_tag, res[1]);
                    }
                    break;
                case REQEEST_CDOE_GPS:
                    binding.llModuleNoUpdate.setVisibility(View.VISIBLE);
                    binding.llModuleUpdate.setVisibility(View.GONE);
                    binding.tvModuleFileUpdate.setText("暂无文件上传");
                    binding.ivModuleUpdate.setTag(R.id.image_tag, null);
                    GlideUtil.setImgMethod(
                            R.drawable.icon_update,
                            binding.ivModuleUpdate
                    );
                    break;
            }
        }
    };
}
